package com.xnck.mfpms.interceptor;

import com.xiaoleilu.hutool.StrUtil;
import com.xnck.mfpms.annotation.Permission;
import com.xnck.mfpms.entity.ResourceInfo;
import com.xnck.mfpms.service.UserService;
import com.xnck.mfpms.util.ContextUtils;
import com.xnck.mfpms.util.SessionUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


/**
 * 权限拦截器
 * @author zhangmengliang
 *
 */
public class PermisInterceptor  extends HandlerInterceptorAdapter {
	protected Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	private UserService userService;
	
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception {
        
    }
 
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView view) throws Exception {
        //如果返回的视图不为NULL，则查找该视图下当前登录人员能够访问的资源，并装载至视图中返回
    	if (view != null) {
        	String userId = this.getCurrentUserId(request);
        	if (StrUtil.isNotBlank(userId) && StrUtil.isNotBlank(view.getViewName())) {
        		List<ResourceInfo> resources = userService.getCanRequestResourcesForView(userId, view.getViewName().toLowerCase());
	    		for (ResourceInfo resource : resources) {
	    			view.addObject(resource.getCode(), true);
	    		}
			}
        }
    }
   
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	//如果拦截的是方法，检查是否有Permission注解，如果有注解则验证是否登录，再验证是否有权限访问注解内标识的资源
    	if (handler instanceof HandlerMethod) {
    		HandlerMethod method = (HandlerMethod)handler;
        	Permission permission = method.getMethodAnnotation(Permission.class);
        	if (null == permission || !StrUtil.isNotBlank(permission.value())) {
    			return true;
    		}
        	String userId = this.getCurrentUserId(request);
        	if (StrUtil.isNotBlank(userId)) {
				Boolean canRequest = userService.getCanRequestResource(userId, permission.value());
				if (canRequest) {
					return true;
				}
			}
        	ContextUtils.responseString(response, "无权限");
        	return false;
    	}
    	return true;
    }
    
    private String getCurrentUserId(HttpServletRequest request){
    	String userId;
    	try {
    		 userId = SessionUtils.getCurrentUserId(request);
		} catch (Exception e) {
			logger.error(e.toString());
			userId = null;
		}
    	return userId;
    }
}
